<template>
  <div>
    <xy-table
      :addFormDTO="addFormDTO"
      :api="api"
      :columns="columns"
    >
      <template #operation>
        <el-table-column
          :label="$language.local('操作')"
          align="center"
          key="ope"
          width="240"
        >
          <template slot-scope="scope">
            <el-row class="center">
              <template v-if="scope.row.CheckStatus != 1">
                <el-col
                  :span="8"
                  class="center"
                >
                  <el-button
                    @click="editItem(scope.row)"
                    size="mini"
                    type="text"
                  >{{ $language.local("修改") }}</el-button>
                </el-col>
                <el-col
                  :span="8"
                  class="center"
                >
                  <el-button
                    @click="onCheck(scope.row)"
                    size="mini"
                    type="text"
                  >{{ $language.local("审核") }}</el-button>
                </el-col>
              </template>
              <template v-else>
                <el-col
                  :span="6"
                  class="center"
                >
                  <el-button
                    @click="onCheck(scope.row)"
                    size="mini"
                    type="text"
                  >{{ $language.local("查看") }}</el-button>
                </el-col>
                <el-col
                  :span="6"
                  class="center"
                >
                  <el-button
                    @click="showSetServiceDialog(scope.row)"
                    size="mini"
                    type="text"
                  >{{ $language.local("设置服务商") }}</el-button>
                </el-col>
              </template>
              <el-col
                :span="6"
                class="center"
              >
                <el-button
                  @click="navContract(scope.row)"
                  class="ml-1"
                  size="mini"
                  type="text"
                >{{ $language.local("合同管理") }}</el-button>
              </el-col>
              <el-col
                :span="6"
                class="center"
              >
                <el-button
                  @click="deleteItem(scope.row)"
                  size="mini"
                  type="text"
                >{{ $language.local("删除") }}</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </template>
    </xy-table>
    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :title="$language.local('设置代理签约服务商')"
      :visible.sync="setServiceVisible"
      width="40%"
    >
      <el-form
        :model="setServiceData"
        :rules="$rules"
        label-width="138px"
        ref="formRef"
        status-icon
      >
        <el-form-item
          :key="index"
          :label="$language.local('authorizeSID') + (index + 1)"
          prop="'authorizeSID'"
          v-for="(item, index) in setServiceData.sids"
        >
          <!-- <select-service v-model="setServiceData.sids[index]"></select-service> -->
          <el-select
            clearable
            v-model="setServiceData.sids[index]"
          >
            <el-option
              :key="item.Id"
              :label="item.ServiceName"
              :value="item.Id.toString()"
              v-for="item in services"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="setServiceData.sids.length < servicesCount">
          <div class="add-form-item">
            <el-tooltip
              :content="$language.local('添加一项')"
              :enterable="false"
              class="item"
              effect="dark"
              placement="top"
            >
              <el-button
                @click="addService"
                icon="el-icon-plus"
                size="mini"
              ></el-button>
            </el-tooltip>
          </div>
        </el-form-item>
      </el-form>
      <span
        class="dialog-footer"
        slot="footer"
      >
        <el-button @click="setServiceVisible = false">
          {{
          $language.local("取消")
          }}
        </el-button>
        <el-button
          @click="onSubmit('formRef')"
          type="primary"
        >
          {{
          $language.local("设置")
          }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from "../../plugins/api";
export default {
  inject: ["reload"],
  data() {
    return {
      api: new API("/api/Agent/"),

      columns: {
        AgentName: "代理商",
        SuperiorAgentName: "渠道",
        // ContactName: "联络人",
        // IdNumber: "编号",
        Phone: "电话",
        // Indate: "创建日期",
        // SignDate: "签约日期",
        // SettlementAccount: "结算账户",
        SettlementBank: "结算银行",
        // ReservedPhone: "预留电话",
        // Region: "地区",
        //  Address: "地址",
        CheckStatus: 1,
      },
      addFormDTO: {
        // SuperiorAgentID: 1,
        SuperiorAgentName: "",
        // customerManagerId: "",
        customerManager: "",
        AgentName: "",
        USCC: "",
        Address: "",
        LegalPersonName: "",
        IdNumber: "",
        ContactName: "",
        Phone: "",
        Region: "",
        SettlementBank: "",
        SettlementAccount: "",
        ReservedPhone: "",
        Rate: null,
        QZDRate: null,
        AgentLevel: null,

        BusinesslicenseImg: null,
        identitycardImg: null,
        identitycardBackImg: null,

        // attfile: "",
        // wmsignuserId: "",
        CheckStatus: null,
        // SettlementInterval: 0,
        // AgreementFile: "",
        // authorizeSID: "2,4,5,6",
        // FileAttId: "b338a80d-e697-4bf7-a8fd-84d9dab9b028",
        // customerManagerId: 79,
      },
      setServiceData: {
        authorizeSID: null,
        sids: "",
      },
      setServiceVisible: false,
      contractDTO: {
        contract: [],
        Id: 48,
        AgentName: "钟平上",
        Phone: "15116228315",
        Address: "1234",
        USCC: "1231",
        SignDate: "2021-06-01T22:23:23",
        SettlementBank: "中国农业银行",
        SettlementAccount: "123",
        Rate: 1,
        QZDRate: 1,
        // SettlementInterval: 0,
        // CheckStatus: 0,
        // SuperiorAgentID: 0,
        // AgentLevel: 0,
        // customerManagerId: 0,
      },
      services: [],
      servicesCount: 0,
    };
  },
  created() {
    this.getData();
  },
  methods: {
    async getData() {
      const responst = await this.$http.get(
        "/api/Common/GetServiceProviderList"
      );
      console.log(responst);
      this.services = responst.data.Data;
      this.servicesCount = responst.TotalCount;
    },
    editItem(item) {
      window.sessionStorage.setItem(
        this.api.entity + "Data",
        JSON.stringify(item)
      );
      this.$router.push({
        path: "/detail",
        query: {
          api: this.api.edit,
          id: item.id || item.Id || item.ID,
        },
      });
    },
    onCheck(item) {
      console.log(item);
      window.sessionStorage.setItem(
        this.api.entity + "Data",
        JSON.stringify(item)
      );
      this.$router.push({
        path: "/detail",
        query: {
          api: this.api.edit,
          id: item.id || item.Id || item.ID,
        },
      });
    },
    async deleteItem(item) {
      let result = await this.$confirm(
        `${this.$language.local("确认删除吗")}？`,
        this.$language.local("提示"),
        {
          confirmButtonText: this.$language.local("确定"),
          cancelButtonText: this.$language.local("取消"),
          type: "warning",
        }
      ).catch((err) => err);

      if (result === "confirm") {
        let id = item["id"] || item["ID"] || item["Id"];
        await this.$http.delete(`${this.api.deleteById}/${id}`, {
          mid: item.MID,
        });

        this.reload();
      } else {
        this.$message.info("已取消");
      }
    },
    async showSetServiceDialog(row) {
      // let response = await this.$http.get(
      //   `/api/Agent/GetAgentService/${row.Id}`
      // );
      // let arr = response.data.Data;
      console.log(row);
      this.setServiceData.sids = row.authorizeSID.split("_");
      this.setServiceData.Id = row.Id;
      this.setServiceVisible = true;
    },
    addService() {
      let length = this.setServiceData.sids.length;
      console.log(this.setServiceData.sids);
      this.setServiceData.sids.push(this.setServiceData.sids[length - 1]);
    },
    async onSubmit() {
      let authorizeSID = this.setServiceData.sids.join("_");
      console.log(authorizeSID);
      // authorizeSID = window.encodeURIComponent(authorizeSID);
      let url = `/api/Agent/SetAgentService/${this.setServiceData.Id}?authorizeSID=${authorizeSID}`;
      console.log(url);
      const response = await this.$http.post(url);
      console.log(response);
      this.setServiceVisible = false;
      this.reload();
    },
    navContract(row) {
      let api = "AgentContract";
      window.sessionStorage.setItem(api, JSON.stringify(this.contractDTO));
      this.$router.push({
        path: "/agent-contract",
        query: {
          id: row.Id,
          api,
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.add-form-item {
  display: flex;
  justify-content: flex-end;
}
.el-form {
  padding-right: 2rem;
}
</style>
